function insert(elem, article, place = 'beforeend') {
  elem.insertAdjacentHTML(
    place,
    '<div class="card">'
    + '<div class="card-body">'
    + article.content
    + '<div class="text-right">'
    + moment(article.publish).fromNow()
    + '</div>'
    + '</div>'
    + '</div>'
  )
}

function fetchPage(page = 0) {
  var myartilces = document.getElementById('myarticles')
  return fetch('./front.do?type=json&page=' + page).then(resp => resp.json())
    .then(articles => {
      articles.forEach(art => insert(myartilces, art))
      return articles
    })
}

var currentPage = 0
var myartilces = document.getElementById('myarticles')
var nextBtn = document.getElementById('next')
var msgTextarea = document.getElementById('input_message')
var publishbtn = document.getElementById('publishbtn')

fetchPage(currentPage)

nextBtn.addEventListener('click', function() {
  nextBtn.setAttribute('disabled', true)
  currentPage++
  fetchPage(currentPage).then(articles => {
    if(articles.length === 5) {
      nextBtn.removeAttribute('disabled')
    } else {
      //TODO:移除按钮
    }
  })
  .catch(console.log)
})



msgTextarea.addEventListener('input', function() {
  var value = msgTextarea.value.trim()
  if(value && value.length > 0 && publishbtn.hasAttribute('disabled')) {
    publishbtn.removeAttribute('disabled')
  }
})

publishbtn.addEventListener('click', function() {
  var msg = msgTextarea.value
  var request = new Request('./publish.do', {
    method: 'POST',
    headers: {
      'Content-Type': 'text/plain'
    },
    body: msg
  })
  fetch(request).then(resp => resp.json())
  .then(article => {
    var container = document.getElementById('text-container')
    msgTextarea.setAttribute('hidden', true)
    container.insertAdjacentHTML(
      'afterbegin',
      '<div class="success-message"><span>成功</span></div>'
    )
    var successMessage = document.querySelector('.success-message')
    successMessage.classList.add('animated', 'bounceInLeft')
    successMessage.addEventListener('animationend', function() {
      insert(myartilces, article, 'afterbegin')
      var first = document.querySelector('#myarticles :first-child')
      first.classList.add('animated', 'bounceInDown')
    }, {once: true})

  })
  .catch(console.log)
})
